<?php

namespace addons\kuerp\model;

use addons\kuerp\model\Form;
use addons\kuerp\model\OperationLog;
use think\Exception;
use think\Model;


class Customers extends Model
{

    // 表名
    protected $name = 'kuerp_customers';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];

    public function getCustomersList(){
        return (new Customertype())->where(['status'=>1])->select();
    }
    public function getSaleList(){
        return (new StaffMember())->where(['status'=>1])->select();
    }

    public function customerlevel()
    {
        return $this->belongsTo('Customerlevel', 'customerlevel_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function customertype()
    {
        return $this->belongsTo('Customertype', 'customertype_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function saler()
    {
        return $this->belongsTo('StaffMember', 'staff_member_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function staff()
    {
        return $this->hasOne(Staff::class, 'id', 'staff_member_id')->field('id,name,admin_id');
    }

    public function getCustomersData($staff_member_ids = []){
        $where = [
            'status'=>1
        ];
        if ($staff_member_ids) {
            $where['staff_member_id'] = ['in', $staff_member_ids];
        }
        return $this->where($where)->select();
    }

    /**
     *修改客户信息
     */
    public static function updateCustomer($params) {
        $operator = $params;
        //自定义字段
        $other = [];
        foreach ($params as $name => $val) {
            if (strstr($name,'other_') !== false) {
                if(is_array($val)){
                    $other[$name] = implode(',',$val);
                }else{
                    $other[$name] = $val;
                }
                unset($params[$name]);
            }
//            else{
//                if($params[$name] === ''){
//                    $params[$name]=NULL;
//                }
//            }
        }
        //操作记录处理
        $form = Form::where(['type' => 'customer'])->find();
        $formdata = json_decode($form['data'],true)['data'];
        $forminfo = [
            'address'=>'地址定位',
            'address_detail'=>'详细地址',
            'country'=>'国家',
            'level'=>'客户星级',
            'management_id'=>'客户所属区域',
            'contract_status'=>'客户成交状态',
            'parent_id'=>'上级公司'
        ];
        foreach($formdata as $k=>$v){
            $forminfo[$v['id']] = $v['config']['label'];
        }
        $customerInfo=self::get($params['id'])->toArray();
        $customer = new self;
        $operation='修改客户信息:将';
        foreach ($operator as $name=>$val){
            if(isset($customerInfo[$name]) && (is_string($customerInfo[$name]) || is_int($customerInfo[$name])) && $customerInfo[$name] != $val){
                $nameinfo = isset($forminfo[$name])?$forminfo[$name]:$name;
                if($nameinfo =='客户成交状态'){
                    if($customerInfo[$name] == 1){
                        $customerInfo[$name] ='已成交';
                    }else{
                        $customerInfo[$name] ='未成交';
                    }
                    if($val == 1){
                        $val ='已成交';
                    }else{
                        $val ='未成交';
                    }
                }
                if($nameinfo =='上级公司'){
                    $customerInfo[$name] = $customer->where(array('id'=>$customerInfo[$name]))->value('name');
                    $val = $customer->where(array('id'=>$val))->value('name');
                }

                $operation.="[{$nameinfo}]【{$customerInfo[$name]}】修改为【{$val}】;";
            }
        }
        if($operation !='修改客户信息:将'){
            OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $params['id'], $operation);
        }

        // 调用当前模型对应的User验证器类进行数据验证
        $result = $customer->save($params, ['id' => $params['id']]);
        if (false === $result) {
            // 验证失败 输出错误信息
            throw new Exception($customer->getError());
        }
        return true;
    }
}
